<template>
  <cardSlot
    v-model="activeName"
    module="webchat_session"
    :tabPanes="tabPanes"
    :cardLoading="loading"
    :isToolbar="true"
    :isShowMore="isShowMore"
    :isShowPage="isShowPage"
    :tabWidth="138"
    :pageData="pageData"
    :empty="!this.webchatList || this.webchatList.length === 0"
    @handleCurrentChange="handleCurrentChange"
    @tab-change="tabChange"
    ref="cardSlot"
  >
    <!-- 会话 -->
    <template slot="toolbar" v-if="activeName === 'webchat_todo'">
      <FunTab
        class="leaveMessageTab"
        :tabs="webchatTapPanes"
        :value="webchatActiveName"
        @input="webchatTabFun"
      >
      </FunTab>
      <!-- 搜索 -->
      <div class="search">
        <el-row class="btn">
          <div
            :style="{
              float: 'left',
              width:
                activeName === 'webchat_todo' &&
                webchatActiveName !== 'webchat_todo'
                  ? '258px'
                  : '300px',
            }"
          >
            <el-input
              class="searchIpt"
              v-model.trim="searchInt"
              placeholder="请输入用户名"
              size="mini"
            >
              <span
                slot="suffix"
                class="V7_iconfont customSearch V7_iconV7tubiao_sousuo"
                @click="searchShowFun"
              ></span>
            </el-input>
          </div>
          <div
            style="float: left; width: 40px"
            v-if="
              activeName === 'webchat_todo' &&
              webchatActiveName == 'webchat_queue'
            "
          >
            <el-popover
              placement="bottom"
              width="340"
              trigger="manual"
              v-model="isShowQueueSearch"
            >
              <el-form
                class="m7-form queueSearchForm"
                size="mini"
                :model="queueSearchForm"
                label-position="top"
              >
                <div class="clearfix">
                  <el-form-item label="时间范围" prop="createTime">
                    <el-date-picker
                      v-model="queueSearchForm.createTime"
                      type="datetimerange"
                      :clearable="false"
                      :picker-options="pickerOptions2"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      format="yyyy-MM-dd HH:mm:ss"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      align="right"
                    >
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="客户名称" prop="visitorName">
                    <el-input
                      v-model="queueSearchForm.visitorName"
                      size="mini"
                      placeholder="请输入客户名称"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="技能组" prop="toPeer">
                    <el-select
                      class="webchatClose"
                      v-model="queueSearchForm.toPeer"
                      placeholder="请选择技能组"
                      size="small"
                      filterable
                      multiple
                      clearable
                      collapse-tags
                    >
                      <el-option
                        v-for="(item, index) in toPeerOpt"
                        :key="index"
                        :label="item.name"
                        :value="item._id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="渠道接入号" prop="accessId">
                    <el-select
                      class="webchatClose"
                      v-model="queueSearchForm.accessId"
                      placeholder="请选择渠道接入号"
                      size="small"
                      filterable
                      multiple
                      clearable
                      collapse-tags
                    >
                      <el-option
                        v-for="(item, index) in accessIdOpt"
                        :key="index"
                        :label="item.name"
                        :value="item.accessId"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="访问来源" prop="seoSource">
                    <el-select
                      class="webchatClose"
                      v-model="queueSearchForm.seoSource"
                      placeholder="请选择访问来源"
                      size="small"
                      filterable
                      multiple
                      clearable
                      collapse-tags
                    >
                      <el-option
                        v-for="(item, index) in seoSourceOpt"
                        :key="index"
                        :label="item.name"
                        :value="item._id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <el-form-item style="textalign: right; width: 100%">
                  <el-button size="mini" @click="isShowQueueSearch = false"
                    >取消</el-button
                  >
                  <el-button
                    size="mini"
                    type="primary"
                    @click="searchCloseFun('queue')"
                    >确定</el-button
                  >
                </el-form-item>
              </el-form>
              <el-button
                size="mini"
                class="V7_iconfont customSearch1 V7_iconV7tubiao_shaixuan"
                slot="reference"
                @click="isShowQueueSearch = !isShowQueueSearch"
              ></el-button>
            </el-popover>
          </div>
          <div
            style="float: left; width: 40px"
            v-if="
              activeName === 'webchat_todo' &&
              webchatActiveName == 'webchat_close'
            "
          >
            <el-popover
              placement="bottom"
              width="440"
              trigger="manual"
              v-model="isShowCloseSearch"
            >
              <el-form
                class="m7-form searchForm"
                size="mini"
                :model="searchForm"
                label-position="top"
              >
                <div class="clearfix">
                  <el-form-item label="客户名称" prop="visitorName" class="fl">
                    <el-input
                      v-model="searchForm.visitorName"
                      size="mini"
                      placeholder="请输入客户名称"
                    ></el-input>
                  </el-form-item>
                  <el-form-item
                    label="会话结束类型"
                    prop="finishKey"
                    class="fl marginLeft"
                  >
                    <el-select
                      class="webchatClose"
                      v-model="searchForm.finishKey"
                      placeholder="请选择会话结束类型"
                      size="small"
                      filterable
                      multiple
                      clearable
                      collapse-tags
                    >
                      <el-option
                        v-for="(item, index) in finishKeyOpt"
                        :key="index"
                        :label="item.name"
                        :value="item._id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="接入号" prop="accessId" class="fl">
                    <el-select
                      class="webchatClose"
                      v-model="searchForm.accessId"
                      placeholder="请选择接入号"
                      size="small"
                      filterable
                      multiple
                      clearable
                      collapse-tags
                    >
                      <el-option
                        v-for="(item, index) in accessIdOpt"
                        :key="index"
                        :label="item.name"
                        :value="item.accessId"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    label="满意度"
                    prop="satisfactionName"
                    class="fl marginLeft"
                  >
                    <el-select
                      class="webchatClose"
                      v-model="searchForm.satisfactionName"
                      placeholder="请选择接入号"
                      size="small"
                      filterable
                      multiple
                      clearable
                      collapse-tags
                    >
                      <el-option
                        v-for="(item, index) in satisfactionOpt"
                        :key="index"
                        :label="item.name"
                        :value="item._id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="创建时间" prop="createTime">
                    <el-date-picker
                      v-model="searchForm.createTime"
                      type="datetimerange"
                      :clearable="false"
                      :picker-options="pickerOptions"
                      range-separator="至"
                      format="yyyy-MM-dd HH:mm:ss"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      align="right"
                    >
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker
                      v-model="searchForm.endTime"
                      type="datetimerange"
                      :clearable="true"
                      format="yyyy-MM-dd HH:mm:ss"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      :picker-options="pickerOptions"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      align="right"
                    >
                    </el-date-picker>
                  </el-form-item>
                </div>
                <el-form-item style="textalign: right; width: 100%">
                  <el-button size="mini" @click="isShowCloseSearch = false"
                    >取消</el-button
                  >
                  <el-button
                    size="mini"
                    type="primary"
                    @click="searchCloseFun('close')"
                    >确定</el-button
                  >
                </el-form-item>
              </el-form>
              <el-button
                size="mini"
                class="V7_iconfont customSearch1 V7_iconV7tubiao_shaixuan"
                slot="reference"
                @click="isShowCloseSearch = !isShowCloseSearch"
              ></el-button>
            </el-popover>
          </div>
        </el-row>
      </div>
      <!-- 处理中 -->
      <div class="function" v-if="webchatActiveName === 'webchat_todo'">
        <!-- 接待上限 -->
        <el-dropdown
          trigger="click"
          @command="limitChange"
          placement="bottom-end"
        >
          <span class="V7_iconfont V7_iconV7tubiao_jiedai"></span>
          <el-dropdown-menu slot="dropdown" class="inDropdown">
            <el-dropdown-item
              v-for="item in limit.options"
              :key="item.value"
              :command="item.value"
              class="numberDropdownItem"
              :class="{ numberActive: limit.value === item.value }"
            >
              {{ item.value }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <!-- 排序 -->
        <el-dropdown
          trigger="click"
          @command="orderChange"
          placement="bottom-start"
        >
          <span class="V7_iconfont V7_iconV7tubiao_zhengxu sortDrop"></span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="(item, index) in sortingOpt"
              :key="index"
              :command="item"
              class="orderDropdownItem"
              :class="{ orderActive: sortingValue === item.value }"
            >
              {{ item.name }}
              <i
                class="checkActive fr"
                :class="{ 'el-icon-check': sortingValue === item.value }"
              ></i>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <!-- 已结束 -->
      <div
        class="function"
        v-if="webchatActiveName === 'webchat_close'"
        style="right: 5px"
      >
        <span
          class="V7_iconfont V7_iconV7tubiao_shuaxin"
          @click="queryWebchatList()"
        ></span>
        <!-- <span class="V7_iconfont V7_iconV7tubiao_zaixian-daochu" style="margin-left:10px"></span> -->
      </div>
      <!-- 排队 -->
      <div class="function" v-if="webchatActiveName === 'webchat_queue'">
        <span
          class="V7_iconfont V7_iconV7tubiao_shuaxin"
          @click="queryWebchatList()"
        ></span>
        <!-- 排序 -->
        <el-dropdown
          trigger="click"
          @command="orderChange"
          placement="bottom-start"
        >
          <span class="V7_iconfont V7_iconV7tubiao_zhengxu sortDrop"></span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="(item, index) in sortingOpt"
              :key="index"
              :command="item"
              class="orderDropdownItem"
              :class="{ orderActive: sortingValue === item.value }"
            >
              {{ item.name }}
              <i
                class="checkActive fr"
                :class="{ 'el-icon-check': sortingValue === item.value }"
              ></i>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </template>
    <!-- 留言 -->
    <template slot="toolbar" v-if="activeName === 'webchat_leaveMessage'">
      <FunTab
        class="leaveMessageTab"
        :tabs="leaveMessageTab"
        :value="leaveMessageActiveName"
        @input="leaveMessageTabFun"
      >
      </FunTab>
      <!-- 搜索 -->
      <div class="search">
        <el-row class="btn">
          <div
            :style="{
              float: 'left',
              width:
                activeName === 'webchat_todo' &&
                webchatActiveName !== 'webchat_todo'
                  ? '258px'
                  : '300px',
            }"
          >
            <el-input
              class="searchIpt"
              v-model.trim="searchInt"
              placeholder="请输入用户名"
              size="mini"
            >
              <span
                slot="suffix"
                class="V7_iconfont customSearch V7_iconV7tubiao_sousuo"
                @click="searchShowFun"
              ></span>
            </el-input>
          </div>
        </el-row>
      </div>
      <!-- 处理中 -->
      <div
        class="function"
        v-if="leaveMessageActiveName === 'leave_todo'"
        style="right: 5px"
      >
        <!-- 接待上限 -->
        <el-dropdown
          trigger="click"
          @command="limitChange"
          placement="bottom-end"
        >
          <span class="V7_iconfont V7_iconV7tubiao_jiedai"></span>
          <el-dropdown-menu slot="dropdown" class="inDropdown">
            <el-dropdown-item
              v-for="item in limit.options"
              :key="item.value"
              :command="item.value"
              class="numberDropdownItem"
              :class="{ numberActive: limit.value === item.value }"
            >
              {{ item.value }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <!-- 留言池 -->
      <div class="function" v-if="leaveMessageActiveName === 'leave_all'"></div>
      <!-- 已处理 -->
      <!-- <div class="function" v-if="leaveMessageActiveName === 'leave_finish'" style="right:5px">
        <span class="V7_iconfont V7_iconV7tubiao_zaixian-daochu" style="margin-left:10px"></span>
      </div> -->
    </template>
    <!-- card列表组件 -->
    <template slot="cardList">
      <webchatCard
        :cardList="webchatList"
        :activeName="activeName"
        :webchatActiveName="webchatActiveName"
        :leaveMessageActiveName="leaveMessageActiveName"
        @iconHandleFun="iconHandleFun"
        @queryWebchatList="queryWebchatList"
      ></webchatCard>
    </template>
  </cardSlot>
</template>
<script lang='ts'>
import { Component, Vue, Watch } from 'vue-property-decorator'
import cardSlot from '@/components/cardLayout/CardSlot.vue'
import FunTab from '@/components/cardLayout/FunTab.vue'
import { isHasFuncOrMenus, getFormatDateTime, commonAction } from '@/utils/common'
import webchatCard from '@/views/webchat/webchatCard.vue'
import { WebchatModule } from '@/store/modules/webchat'
import { ArrayObj, OrderObj } from '@/views/webchat/webchatInterface'
import { CommonModule } from '@/store/modules/common'
@Component({
  name: 'webchatCardGroup',
  components: { cardSlot, webchatCard, FunTab }
})
export default class WebchatCardGroup extends Vue {
  private $router: any
  private $store: any
  private $bus: any
  private $route: any
  private $message: any
  private $getCache: any
  private currentWebchatUrl: string = '' // 当前会话路由路径
  private currentLeaveUrl: string = '' // 当前留言路由路径

  private isShowMore: boolean = false // 是否展示查看更多

  private isShowPage: boolean = false // 是否展示翻页

  private isShowCloseSearch: boolean = false // 是否展示已结束高级搜索

  private isShowQueueSearch: boolean = false // 是否展示排队中高级搜索

  private isQueueTotal: boolean = false // 排队数取值

  private searchInt: string = '' // 搜索客户名称

  private leaveAllListCount: number = 0 // 留言总数

  private sortingValue: string = 'lastMessageTimestamp' // 排序

  private pickerOptions = {
    shortcuts: [{
      text: '最近一周',
      onClick (picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        picker.$emit('pick', [start, end]);
      }
    }, {
      text: '最近一个月',
      onClick (picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        picker.$emit('pick', [start, end]);
      }
    }, {
      text: '最近三个月',
      onClick (picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        picker.$emit('pick', [start, end]);
      }
    }]
  }

  private pickerOptions2 = {
    shortcuts: [{
      text: '昨天',
      onClick (picker) {
        const end = getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 1), '').split(' ')[0] + ' 23:59:59'
        const start = getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 1), '').split(' ')[0] + ' 00:00:00'
        picker.$emit('pick', [start, end]);
      }
    }, {
      text: '今天',
      onClick (picker) {
        const end = getFormatDateTime(new Date(), '').split(' ')[0] + ' 23:59:59'
        const start = getFormatDateTime(new Date(new Date().getTime()), '').split(' ')[0] + ' 00:00:00'
        picker.$emit('pick', [start, end]);
      }
    },
    {
      text: '最近一周',
      onClick (picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        const startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0)
        const endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)
        picker.$emit('pick', [startTime, endTime]);
      }
    }, {
      text: '最近一个月',
      onClick (picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        const startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0)
        const endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)
        picker.$emit('pick', [startTime, endTime]);
      }
    }]
  }

  private searchForm = { // 已结束会话高级搜索
    visitorName: '', // 客户名称
    finishKey: [], // 会话结束类型
    accessId: [], // 接入号
    satisfactionName: [], // 满意度
    createTime: [ // 创建时间默认显示近一周
      getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 6), '').split(' ')[0] + ' 00:00:00',
      getFormatDateTime(new Date(), '').split(' ')[0] + ' 23:59:59'
    ],
    endTime: [ // 结束时间 默认显示近一天
      getFormatDateTime(new Date(new Date().getTime()), '').split(' ')[0] + ' 00:00:00',
      getFormatDateTime(new Date(), '').split(' ')[0] + ' 23:59:59'
    ]
  }

  private queueSearchForm = { // 排队会话高级搜索
    visitorName: '', // 客户名称
    createTime: [ // 时间范围
      getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 6), '').split(' ')[0] + ' 00:00:00',
      getFormatDateTime(new Date(), '').split(' ')[0] + ' 23:59:59'
    ],
    toPeer: [], // 技能组
    accessId: [], // 接入号
    seoSource: [] // 访问来源
  }

  private leaveFinishSearch = { // 已处理默认时间条件
    createTime: [ // 时间范围
      getFormatDateTime(new Date(new Date().getTime()), '').split(' ')[0] + ' 00:00:00',
      getFormatDateTime(new Date(), '').split(' ')[0] + ' 23:59:59'
    ],
    visitorName: ''
  }

  private leaveSearch = { // 留言条件
    visitorName: ''
  }

  private leaveAllSearch = { // 留言条件
    visitorName: ''
  }

  private leaveMessagePageData: any = { // 留言翻页
    total: 0,
    pageSize: 10,
    currentPage: 1
  }

  private pageData: any = {
    total: 0,
    pageSize: 10,
    currentPage: 1
  }

  private closePageData: any = { // 已结束翻页
    total: 0,
    pageSize: 10,
    currentPage: 1
  }

  // 排队中翻页
  private queuePageData: any = {
    total: 0,
    pageSize: 10,
    currentPage: 1
  }

  private finishKeyOpt: any = []

  private satisfactionOpt: any = []

  private seoSourceOpt: any = []

  private webchatQueueCount: any = '' // 排队数

  private toPeerOpt: any = []

  private sortingOpt: any = [ // 排序选项
    { name: '最新消息', value: 'lastMessageTimestamp' },
    { name: '接入顺序', value: 'manualTimestamp' },
    { name: '访客等待时长', value: 'visitorStartWaitTimestamp' }
  ]

  private limit: any = { // 会话上限
    options: [], // 下拉选项
    value: 1 // 当前选中值
  }

  private leaveMessageTab: any = [
    { label: '处理中0/0', name: 'leave_todo' },
    { label: '留言池', name: 'leave_all' },
    { label: '已处理', name: 'leave_finish' }
  ]

  private webchatActiveName: string = 'webchat_todo'

  private leaveMessageActiveName: string = 'leave_todo' // 留言默认tab

  private activeName: string = 'webchat_todo' // 当前所在的tab

  private loading: boolean = false // 是否加载成功

  get accessIdOpt () {
    return this.$store.state.common.publicCache.channelList || []
  }

  get webchatTapPanes () {
    const webchatTodoList = this.$store.state.webchat.webchatList.webchat_todo || [] // 当前待处理下的会话列表
    const webchatQueueList = this.$store.state.webchat.webchatUnDealNum || '' // 当前排队中下的会话列表
    const webchatCloseList = this.$store.state.webchat.webchatList.webchat_close || [] // 当前排队中下的会话列表
    const isShowTodoHot = webchatTodoList.find(item => {
      return item.leakNum > 0
    })
    const isShowCloseHot = webchatCloseList.find(item => {
      return item.leakNum > 0
    })
    return [
      { label: `处理中${webchatTodoList.length}/${this.limit.value}`, name: 'webchat_todo', isShowHot: !!isShowTodoHot, color: 'red' },
      { label: `排队中${this.webchatQueueCount > 0 ? this.webchatQueueCount : webchatQueueList}`, name: 'webchat_queue' },
      { label: '已结束', name: 'webchat_close', isShowHot: !!isShowCloseHot, color: '#BABDC3' }
    ]
  }

  get tabPanes () { // tab上的未读数
    const webchatTodoList = this.$store.state.webchat.webchatList.webchat_todo || [] // 当前待处理下的会话列表
    if (!this.isQueueTotal) {
      this.webchatQueueCount = (this as any).webchatQueueCount
      this.isQueueTotal = !this.isQueueTotal
    } else {
      this.webchatQueueCount = this.$store.state.webchat.webchatUnDealNum || '' // 当前排队中下的会话列表
    }
    const total = this.webchatQueueCount + webchatTodoList.length
    const leaveNum = this.$store.state.webchat.leaveNume || 0
    this.leaveAllListCount = (Number(this.leaveAllListCount) + Number(leaveNum))
    WebchatModule.SET_LEAVE_NUM(0)
    return [
      { name: '会话(' + total + ')', type: 'webchat_todo' },
      { name: '留言(' + this.leaveAllListCount + ')', type: 'webchat_leaveMessage' }
    ]
  }

  get webchatList () { // 获取会话列表
    let webchatList = this.$store.state.webchat.webchatList[this.activeName] || []
    if (this.activeName === 'webchat_leaveMessage') { // 留言会话取留言的tab上的数据
      webchatList = this.$store.state.webchat.webchatList[this.leaveMessageActiveName] || []
    } else if (this.activeName === 'webchat_todo') { // 会话取会话tab上的数据
      webchatList = this.$store.state.webchat.webchatList[this.webchatActiveName] || []
    }
    if (this.activeName === 'webchat_todo' && this.webchatActiveName === 'webchat_todo') {
      webchatList = webchatList.filter((item: any) => { // 待处理会话筛选
        return item.visitorName.indexOf(this.searchInt) > -1
      })
    }
    console.log(webchatList, '列表数据')
    return webchatList
  }

  get sessionId () {
    return this.$route.path.split('/')[4]
  }

  private searchShowFun () {
    if ((this.activeName === 'webchat_todo' && this.webchatActiveName !== 'webchat_todo')) {
      if (this.webchatActiveName === 'webchat_close') {
        this.searchForm.visitorName = this.searchInt
        this.closePageData.currentPage = 1
      } else {
        this.queueSearchForm.visitorName = this.searchInt
        this.queuePageData.currentPage = 1
      }
    }
    if (this.activeName === 'webchat_leaveMessage' && this.leaveMessageActiveName === 'leave_finish') {
      this.leaveFinishSearch.visitorName = this.searchInt
      this.leaveMessagePageData.currentPage = 1
    } else if (this.activeName === 'webchat_leaveMessage' && this.leaveMessageActiveName === 'leave_todo') {
      this.leaveSearch.visitorName = this.searchInt
      this.leaveMessagePageData.currentPage = 1
    } else {
      this.leaveAllSearch.visitorName = this.searchInt
      this.leaveMessagePageData.currentPage = 1
    }
    this.queryWebchatList()
  }

  private handleCurrentChange (val: number) { // 留言翻页
    if (this.activeName === 'webchat_todo') {
      if (this.webchatActiveName === 'webchat_queue') {
        this.queuePageData.currentPage = val
      } else {
        this.closePageData.currentPage = val
      }
    } else {
      this.leaveMessagePageData.currentPage = val
    }
    this.queryWebchatList()
  }

  private webchatTabFun (type: string) { // 会话tab切换
    this.searchInt = ''
    this.webchatActiveName = type
    const webchatSession: any = window.sessionStorage
    if (type === 'webchat_todo') { // 处理中
      const currentTodoUrlObj = webchatSession.getItem('webchatTab') || ''
      if (currentTodoUrlObj) {
        this.$router.push({ path: currentTodoUrlObj })
      } else {
        this.$router.push({ path: '/im_workBench/index/webchat_todo/empty' })
      }
      if (isHasFuncOrMenus('webchat_session', this.$store.state.common.session.user, true)) { // 是否有在线记录的权限
        this.isShowMore = true
      }
      this.isShowPage = false
      this.pageData = this.closePageData
    } else if (type === 'webchat_queue') { // 排队中
      this.isShowMore = false
      this.isShowPage = true
      const currentQueueUrlObj = webchatSession.getItem('webchatQueueTab') || ''
      if (currentQueueUrlObj) {
        this.$router.push({ path: currentQueueUrlObj })
      } else {
        this.$router.push({ path: '/im_workBench/index/webchat_queue/empty' })
      }
      this.pageData = this.queuePageData
    } else { // 结束
      this.isShowMore = false
      this.isShowPage = true
      const currentCloseUrlObj = webchatSession.getItem('webchatCloseTab') || ''
      if (currentCloseUrlObj) {
        this.$router.push({ path: currentCloseUrlObj })
      } else {
        this.$router.push({ path: '/im_workBench/index/webchat_close/empty' })
      }
      this.pageData = this.closePageData
    }
    this.queryWebchatList()
  }

  private leaveMessageTabFun (type: string) { // 留言tab切换
    this.searchInt = ''
    this.leaveMessageActiveName = type
    const webchatSession: any = window.sessionStorage
    if (type === 'leave_todo') {
      this.leaveSearch.visitorName = ''
      const currentLeaveTodoUrlObj = webchatSession.getItem('leaveTab') || ''
      if (currentLeaveTodoUrlObj) {
        this.$router.push({ path: currentLeaveTodoUrlObj })
      } else {
        this.$router.push({ path: '/im_workBench/index/webchat_leaveMessage/empty' })
      }
    } else if (type === 'leave_all') {
      this.leaveAllSearch.visitorName = ''
      const currentLeaveTodoUrlObj = webchatSession.getItem('leaveAllTab') || ''
      if (currentLeaveTodoUrlObj) {
        this.$router.push({ path: currentLeaveTodoUrlObj })
      } else {
        this.$router.push({ path: '/im_workBench/index/webchat_leaveMessage/empty' })
      }
    } else {
      this.leaveFinishSearch.visitorName = ''
      const currentLeaveTodoUrlObj = webchatSession.getItem('leaveCloseTab') || ''
      if (currentLeaveTodoUrlObj) {
        this.$router.push({ path: currentLeaveTodoUrlObj })
      } else {
        this.$router.push({ path: '/im_workBench/index/webchat_leaveMessage/empty' })
      }
    }
    this.leaveMessagePageData.currentPage = 1 // 切换留言子tab需要把当前页归1
    this.queryWebchatList() // 留言会话需要实时获取列表数据
  }

  private orderChange (data: OrderObj) { // 会话排序事件
    this.sortingValue = data.value
    const currentUser = this.$store.state.common.session.account.loginName + '@' + this.$store.state.common.session.account._id
    window.localStorage.setItem(currentUser + '/sortType', data.value)
    WebchatModule.SORTLISTBY_TYPE(this.webchatActiveName) // 更新会话顺序
  }

  private iconHandleFun (id) { // 卡片上的icon点击事件
    if (this.activeName === 'webchat_todo') {
      if (this.webchatActiveName === 'webchat_queue') {
        this.queuePageData.currentPage = 1
      } else {
        this.closePageData.currentPage = 1
      }
    } else {
      this.leaveMessagePageData.currentPage = 1 // 切换留言子tab需要把当前页归1
    }
    const webchatSession = window.sessionStorage
    // 当会话id等于当前id时重置记忆路由
    if (this.activeName === 'webchat_todo') {
      const tabSessionId = webchatSession.getItem('webchatQueueTab')?.split('/')[4]
      const closeTabSessionId = webchatSession.getItem('webchatQueueTab')?.split('/')[4]
      if (this.webchatActiveName === 'webchat_queue' && tabSessionId === id) {
        webchatSession.setItem('webchatQueueTab', '/im_workBench/index/webchat_queue/empty')
      } else if (this.webchatActiveName === 'webchat_close' && closeTabSessionId === id) {
        webchatSession.setItem('webchatCloseTab', '/im_workBench/index/webchat_close/empty')
      }
    } else {
      const leavetodoTabSessionId = webchatSession.getItem('leaveTab')?.split('/')[4]
      const leavefinishTabSessionId = webchatSession.getItem('leave_finish')?.split('/')[4]
      const leaveallTabSessionId = webchatSession.getItem('leaveAllTab')?.split('/')[4]
      console.log(leaveallTabSessionId, id, 'id')
      if (this.leaveMessageActiveName === 'leave_finish' && leavefinishTabSessionId === id) {
        webchatSession.setItem('leaveCloseTab', '/im_workBench/index/webchat_leaveMessage/empty')
      }
      if (this.leaveMessageActiveName === 'leave_all' && leaveallTabSessionId === id) {
        webchatSession.setItem('leaveAllTab', '/im_workBench/index/webchat_leaveMessage/empty')
      }
      if (this.leaveMessageActiveName === 'leave_todo' && leavetodoTabSessionId === id) {
        webchatSession.setItem('leaveTab', '/im_workBench/index/webchat_leaveMessage/empty')
      }
    }
    this.queryWebchatList()
  }

  private limitChange (time?: string) { // 会话上限改变
    if (time !== 'first') {
      this.limit.value = time
    }
    const actionData = { url: '/im-center/action/webchat/updateUserSessionLimit', method: 'POST', data: { imDealCount: this.limit.value, socketId: this.$store.state.socketIo.lastSocketId } }
    WebchatModule.webchatCommonAction(actionData).then(res => {
      if (res) {
        if (time !== 'first') { // 第一次在线咨询工作台 点击的时候不去提示
          this.$message.success('更改会话上限成功')
        }
      }
    })
  }

  private searchCloseFun (flag) { // 已结束搜索
    const createTime: any = this.searchForm.createTime
    if (createTime && createTime[0] && createTime[1]) {
      let sTime: any = 0
      let eTime: any = 0
      if (typeof createTime[0] === 'string') {
        sTime = new Date(createTime[0]).getTime()
        eTime = new Date(createTime[1]).getTime()
      } else {
        sTime = createTime[0].getTime()
        eTime = createTime[1].getTime()
      }
      const oneDay: any = 1000 * 3600 * 24
      const day: any = (eTime - sTime) / oneDay
      const Days: any = parseInt(day, 10)
      if (Days > 31 * 12) { // ss
        this.$message.error('请选择12个月之内的创建时间')
        return
      }
    } else {
      this.$message.error('请选择12个月之内的创建时间')
      return
    }
    if (flag === 'close') {
      this.closePageData.currentPage = 1
      this.isShowCloseSearch = false
    } else {
      this.queuePageData.currentPage = 1
      this.isShowQueueSearch = false
    }
    this.queryWebchatList()
  }

  private tabChange (type: string) { // tab切换
    this.searchInt = ''
    this.activeName = type
    const webchatSession: any = window.sessionStorage
    let currentUrlObj = webchatSession.getItem('webchatTab') || ''
    if (type === 'webchat_todo') { // 会话
      if (this.webchatActiveName === 'webchat_close') { // 会话已结束
        currentUrlObj = webchatSession.getItem('webchatCloseTab') || ''
      } else if (this.webchatActiveName === 'webchat_queue') { // 会话排队中
        currentUrlObj = webchatSession.getItem('webchatQueueTab') || ''
        this.pageData = this.queuePageData
      } else {
        this.pageData = this.closePageData
      }
      if (currentUrlObj) {
        this.$router.push({ path: currentUrlObj })
      } else {
        if (webchatSession.getItem('webchatTab')) {
          const url = webchatSession.getItem('webchatTab')
          this.$router.push({ path: url })
        } else {
          this.$router.push({ path: '/im_workBench/index/webchat_todo/empty' })
        }
      }
      if (this.webchatActiveName === 'webchat_todo') { // 会话处理中
        if (isHasFuncOrMenus('webchat_session', this.$store.state.common.session.user, true)) { // 是否有在线记录的权限
          this.isShowMore = true
        }
        this.isShowPage = false
      } else {
        this.isShowMore = false
        this.isShowPage = true
      }
    } else { // 留言
      this.isShowPage = true
      this.isShowMore = false
      let currentLeaveUrlObj = webchatSession.getItem('leaveTab') || ''
      if (this.leaveMessageActiveName === 'leave_finish') { // 留言已处理
        currentLeaveUrlObj = webchatSession.getItem('leaveCloseTab') || ''
      } else if (this.leaveMessageActiveName === 'leave_all') { // 留言池
        currentLeaveUrlObj = webchatSession.getItem('leaveAllTab') || ''
      }
      if (currentLeaveUrlObj) {
        this.$router.push({ path: currentLeaveUrlObj })
      } else {
        if (webchatSession.getItem('leaveTab')) {
          const leaveUrl = webchatSession.getItem('leaveTab')
          this.$router.push({ path: leaveUrl })
        } else {
          this.$router.push({ path: `/im_workBench/index/${type}/empty` })
        }
      }
      this.pageData = this.leaveMessagePageData
      this.queryWebchatList() // 留言会话需要实时获取列表数据
      this.pageData = this.leaveMessagePageData
    }
    this.$nextTick(() => {
      (this.$refs as any).cardSlot.scrollRefresh()
    })
    this.$bus.$emit('webchatTabChange')
  }

  private getFetchData () { // 处理会话信息和会话历史
    let chatInfoUrl = '/im-center/action/webchat/queryChatInfoById'
    let webchatType = 'webchat_todo'
    if (this.activeName === 'webchat_leaveMessage') { // 留言会话详情接口路径
      chatInfoUrl = '/im-center/action/webchat/queryLeaveSessionInfoById'
      webchatType = 'webchat_leaveMessage'
    } else { // 会话
      if (this.webchatActiveName === 'webchat_queue') {
        webchatType = 'webchat_queue'
      }
      if (this.webchatActiveName === 'webchat_close') {
        webchatType = 'webchat_close'
      }
    }
    const chatInfoActionData = { url: chatInfoUrl, method: 'POST', data: { _id: this.sessionId } }
    const queryChatInfoById = WebchatModule.queryChatInfoById(chatInfoActionData) // 获取会话详情
    Promise.all([queryChatInfoById]).then(resp => {
      if (resp && resp[0] && resp[0].success) {
        const currentHistory = WebchatModule.webchatMessage.webchat_todo ? WebchatModule.webchatMessage.webchat_todo[this.sessionId] : []
        const chatSession = resp[0].chatSession
        const processInfo = resp[0].scheduleHistory
        const visitorInfo = resp[0].visitorInfo || {}
        if (currentHistory && currentHistory.length > 0 && this.activeName === 'webchat_todo' && this.webchatActiveName === 'webchat_todo') { // 加载过聊天历史不在重新请求接口
          this.$bus.$emit('renderWebchatSummary', { chatSession, processInfo, visitorInfo }) // 通知渲染右侧组件
          return
        }
        const serveTimeActionData = { url: '/im-center/action/webchat/getServerTimeDiff', method: 'POST', data: { localTimestamp: new Date().getTime() } }
        WebchatModule.webchatCommonAction(serveTimeActionData).then(serverTime => { // 获取当前服务器时间戳，根据当前时间戳去获取聊天历史
          const messageHistoryData = { // 获取消息历史参数
            visitorId: chatSession.visitorId, // 访客id
            dateTime: serverTime.serverTime, // 当前服务器时间
            limit: 20, // 请求聊天历史的条数
            _id: this.sessionId, // 会话id
            isNewSession: true, // 是否是新接入的会话
            webchatType
          }
          const messageHistoryActionData = { url: '/im-center/action/webchat/queryHistory', method: 'POST', data: messageHistoryData } // 获取聊天历史
          WebchatModule.queryWebchatHistory(messageHistoryActionData).then(messageList => {
            if (messageList) {
              this.$bus.$emit('renderWebchatSummary', { chatSession, processInfo, visitorInfo }) // 通知渲染右侧组件
            }
          })
        })
        this.$emit('getWebchatSessionInfo', resp)
      }
    })
  }

  private queryWebchatList (callback?: any) { // 查询会话列表
    let sendData: any = {
      submenu: this.activeName // 菜单类型
    }
    let url = '/im-center/action/webchat/queryWebchatSession'
    if (this.activeName === 'webchat_leaveMessage') { // 查询留言列表数据
      sendData.submenu = this.leaveMessageActiveName
      url = '/im-center/action/webchat/queryLeaveSession'
      if (this.leaveMessageActiveName === 'leave_finish') { // 已处理
        sendData.limit = 10
        sendData = Object.assign(sendData, { ...this.leaveFinishSearch })
      } else if (this.leaveMessageActiveName === 'leave_todo') {
        sendData.limit = 10
        sendData.visitorName = this.leaveSearch.visitorName
      } else {
        sendData.limit = 10
        sendData.visitorName = this.leaveAllSearch.visitorName
      }
      sendData.page = this.leaveMessagePageData.currentPage
    } else if (this.activeName === 'webchat_todo') { // 会话
      sendData.submenu = this.webchatActiveName
      if (this.webchatActiveName === 'webchat_queue') { // 排队
        sendData.limit = 10
        sendData.page = this.queuePageData.currentPage
        sendData = Object.assign(sendData, { ...this.queueSearchForm })
      } else { // 会话处理中/已结束
        sendData.limit = 10
        sendData.page = this.closePageData.currentPage
        sendData = Object.assign(sendData, { ...this.searchForm })
      }
    }
    const actionData = { url, method: 'POST', data: sendData }
    WebchatModule.getWebchatList(actionData).then(res => {
      if (res && this.activeName === 'webchat_leaveMessage') {
        this.leaveAllListCount = res.todoListCount + res.allListCount
        if (this.leaveMessageActiveName === 'leave_todo') {
          this.leaveMessagePageData.total = res.todoListCount
        } else if (this.leaveMessageActiveName === 'leave_finish') {
          this.leaveMessagePageData.total = res.finishListCount
        } else {
          this.leaveMessagePageData.total = res.allListCount
        }
        this.leaveMessageTab = [
          { label: `处理中${res.todoListCount}`, name: 'leave_todo' }, // 处理中留言总数
          { label: `留言池${res.allListCount}`, name: 'leave_all' }, // 全部留言总数
          { label: '已处理', name: 'leave_finish' } // 已处理留言总数
        ]
      }
      if (res && this.activeName === 'webchat_todo' && this.webchatActiveName === 'webchat_queue') {
        this.queuePageData.total = res.count || 0
        this.webchatQueueCount = res.count || ''
        this.isQueueTotal = false
      } else {
        this.closePageData.total = res.count || 0
      }
      if (res && callback) {
        callback()
      }
      const cusTomerIdArr: any = []
      if (res && res.list.length > 0) {
        res.list.map(item => {
          if (item.customerId) {
            cusTomerIdArr.push(item.customerId)
          }
        })
      }
      const params = {
        url: '/server-crm/action/customer/listLabelsByIds',
        method: 'post',
        data: { ids: cusTomerIdArr }
      }
      if (cusTomerIdArr.length > 0) {
        // 请求客户标签，并返回列表上
        if (this.$store.state.common.session.account.mpShifted) {
          commonAction(params).then(resp => {
            if (resp && resp.success && resp.data) {
              const resList = resp.data || []
              Object.keys(resList).forEach(i => {
                if (res && res.list.length > 0) {
                  res.list.forEach(item => {
                    if (item.customerId && item.customerId === i) {
                      Vue.set(item, 'labels', resList[i])
                    }
                  })
                }
              })
            }
          })
        }
      }
    })
  }

  // 搜索栏中高级搜索展示隐藏
  private queueCustomSearchShow () {
    if (this.webchatActiveName !== 'webchat_todo') {
      this.isShowCloseSearch = true
    } else {
      this.isShowCloseSearch = false
    }
  }

  @Watch('$route')
  private routeChange (to: any, from: any) {
    const routeArr = to.path.split('/')
    const webchatSession = window.sessionStorage
    if (routeArr[1] === 'im_workBench' && routeArr[3] === 'webchat_todo') {
      this.activeName = 'webchat_todo'
      this.webchatActiveName = 'webchat_todo'
      this.isShowPage = false
      if (isHasFuncOrMenus('webchat_session', this.$store.state.common.session.user, true)) { // 是否有在线记录的权限
        this.isShowMore = true
      }
    }
    if (routeArr[1] === 'im_workBench' && routeArr.length > 4 && routeArr[4] !== 'empty') {
      if (this.activeName === 'webchat_todo') { // 会话需要记住上次点击的会话
        this.currentWebchatUrl = to.fullPath
        if (this.webchatActiveName === 'webchat_todo') {
          webchatSession.setItem('webchatTab', this.currentWebchatUrl)
        } else if (this.webchatActiveName === 'webchat_queue') {
          webchatSession.setItem('webchatQueueTab', this.currentWebchatUrl)
        } else {
          webchatSession.setItem('webchatCloseTab', this.currentWebchatUrl)
        }
      }
      if (this.activeName === 'webchat_leaveMessage') { // 留言需要记住上次点击的会话
        this.currentLeaveUrl = to.fullPath
        if (this.leaveMessageActiveName === 'leave_todo') {
          webchatSession.setItem('leaveTab', this.currentLeaveUrl)
        } else if (this.leaveMessageActiveName === 'leave_all') {
          webchatSession.setItem('leaveAllTab', this.currentLeaveUrl)
        } else {
          webchatSession.setItem('leaveCloseTab', this.currentLeaveUrl)
        }
      }
      this.getFetchData()
    }
  }

  @Watch('webchatList')
  private webchatListChange () {
    this.$nextTick(() => {
      (this.$refs as any).cardSlot.scrollRefresh()
    })
  }

  private getDiffTime () {
    const serveTimeActionData = { url: '/im-center/action/webchat/getServerTimeDiff', method: 'POST', data: { localTimestamp: new Date().getTime() } }
    WebchatModule.webchatCommonAction(serveTimeActionData).then(serverTime => { // 获取当前服务器时间戳，根据当前时间戳去获取聊天历史
      CommonModule.setDiffTime(serverTime.diff) // 本地时间和服务器时间差
    })
  }

  private mounted () {
    this.getDiffTime()
    if (this.activeName === 'webchat_todo') {
      this.currentWebchatUrl = this.$route.fullPath
      if (this.webchatActiveName === 'webchat_queue') {
        this.pageData = this.queuePageData
      } else {
        this.pageData = this.closePageData
      }
    } else {
      this.pageData = this.leaveMessagePageData
    }
    const types = { types: ['userConfig'] }
    const actionData = { url: '/im-center/action/webchat/getImGlobalConfig', method: 'POST', data: types }
    WebchatModule.webchatCommonAction(actionData).then(res => {
      if (res && res.webchatUserConfig) { // 会话上限处理
        const limit = res.webchatUserConfig
        const max = limit.maxLimit // 会话上限最大值
        const min = limit.minLimit // 会话上限最小值
        let limitValue = limit.imDealCount || 1
        if (limitValue < min) { // 当前选中值小于最小限制取最小限制值
          limitValue = min
        } else if (limitValue > max) { // 当前选中值大于最大限制取最大限制值
          limitValue = max
        }
        this.limit.value = limitValue
        for (let i = min; i <= max; i++) {
          this.limit.options.push({ label: i, value: i })
        }
        this.limitChange('first')
      }
    })
    const webchatType = ['finishKey', 'satisfactionName', 'sessionTags', 'seoSource'] // 在线缓存
    this.$getCache('/im-center/action/webchat/cache', webchatType, true, true, true, 'POST', true).then((res: any) => {
      if (res && res.success) {
        this.finishKeyOpt = res.finishKey
        this.satisfactionOpt = res.satisfactionName
        this.seoSourceOpt = res.seoSource
      }
    })
    this.$getCache('/im-center/action/webchat/channelCache', ['channelList'], true)
    this.toPeerOpt = this.$store.state.common.publicCache.queueList || []
    this.queryWebchatList(() => {
      WebchatModule.webchatList[this.activeName].forEach((item: any) => {
        if (item._id === this.sessionId) { // 找到当前会话去获取会话信息和会话历史
          this.getFetchData()
        }
      })
    })
    if (isHasFuncOrMenus('webchat_session', this.$store.state.common.session.user, true)) { // 是否有在线记录的权限
      this.isShowMore = true
    }
    const currentUser = this.$store.state.common.session.account.loginName + '@' + this.$store.state.common.session.account._id
    const sortType = window.localStorage.getItem(currentUser + '/sortType') || 'lastMessageTimestamp' // 会话排序取值
    this.orderChange({ value: sortType })
    this.$bus.$on('dealLeaveMessage', () => {
      this.queryWebchatList()
    });
    const url = '/im-center/action/webchat/queryLeaveSession'
    const sendData: any = {
      submenu: 'webchat_leaveMessage' // 菜单类型
    }
    sendData.submenu = this.leaveMessageActiveName
    sendData.limit = 10
    sendData.page = this.leaveMessagePageData.currentPage
    const data = { url, method: 'POST', data: sendData }
    WebchatModule.getWebchatList(data).then(res => {
      this.leaveAllListCount = res.allListCount + res.todoListCount
    })
  }

  private beforeDestroy () {
    this.$bus.$off('dealLeaveMessage')
  }
}
</script>
<style lang="stylus" scoped>
.limitTitle
  font-size 12px
  color #303753
  margin-bottom 10px
.limitSelect
  margin-right 8px
.searchIpt
  width 100%
.sortDrop
  position absolute
  left 8px
  bottom -3px
.V7_iconV7tubiao_shaixuan
  padding 7px 8px 8px
  border 1px solid #DCDFE6
  border-radius 4px
  margin-left 4px
.checkActive
  line-height 34px
  font-size 12px
  width 12px
  display inline-block
  color #459AE9
.orderActive
  background #EDF5FD
  color #459AE9
.numberActive
  color #459AE9
.inDropdown
  width 8%
  max-height 200px
  overflow-y scroll
.orderDropdownItem
  text-align left
.numberDropdownItem
  text-align left
.function
  position absolute
  right 23px
  top 15px
.V7_iconfont
  font-size 14px
  cursor pointer
  color #A6A6AE
.V7_iconV7tubiao_sousuo, .V7_iconV7tubiao_guanbi
  margin-left 10px
.search
  .customSearch
    width 26px
    height 30px
    display inline-block
.btn
  .customSearch1
    width 32px
    height 32px
    margin-left 10px
    padding-left 8px
.searchForm
  >>>.el-select--mini
    width 100%
  >>>.el-form-item--mini
    width 47%
.marginLeft
  margin-left 20px
.funTab
  height 48px
  margin-bottom 10px
  padding 21px 0px 0px 10px
  border-bottom 1px solid $border-main
  color #767E91
  .el-icon-info
    margin-right 6px
    color #FAAD14
.queueSearchForm
  >>>.el-date-editor
    width 100%
  .el-select
    width 100%
.dateTitle
  height 45px
  line-height 45px
  color #303753
  font-weight 600
  padding 0px 16px
  border-bottom 1px solid $border-main
</style>
<style lang="stylus">
.leaveMessageTab
  .el-tabs__item
    padding 0 15px !important
  .el-tabs__nav-wrap::after
    height 1px !important
</style>
